# -*- coding: utf-8 -*-
"""
@Author : xh
@Time   : 2023/10/29 18:24
"""
from flask import Flask, request
from flask_cors import CORS
import json
import time
import logging

from config import ERRCD
from solver import auto_solver

logger = logging.getLogger(__name__)
logging.basicConfig(format='%(asctime)s - %(levelname)s: %(message)s', level=logging.DEBUG)

app = Flask(__name__)
app.config.from_object(__name__)
CORS(app)


@app.route("/solve", methods=["GET", "POST"])
def solve():
    """
    主函数
    """
    start = time.time()
    rep = {}
    try:
        rdata = request.json
        logger.info('[SUC] Input: %s' % json.dumps(rdata, ensure_ascii=False))
    except Exception as E:
        rep['msg'] = ERRCD[-98]
        logger.info('[BUG] %s ' % ERRCD[-15] + str(E))
        rep['code'] = -98
        rep['result'] = {}
        rep["cost"] = "{:.2f} ms".format((time.time() - start) * 1000)
        return json.dumps(rep, ensure_ascii=False)

    try:
        result = auto_solver(rdata)
    except Exception as E:
        rep["msg"] = ERRCD[-99]
        logger.info('[BUG] Msg: %s' % (ERRCD[-99] + str(E)))
        rep["code"] = -99
        rep["result"] = {}
        rep["cost"] = "{:.2f} ms".format((time.time() - start) * 1000)
        return json.dumps(rep, ensure_ascii=False)

    rep["code"] = result["code"]
    rep["msg"] = ERRCD[result["code"]]
    rep["result"] = result["result"]
    rep["cost"] = "{:.2f} ms".format((time.time() - start) * 1000)
    logger.info(f"[SUC] Input: {json.dumps(rdata, ensure_ascii=False)}, Output: {json.dumps(rep, ensure_ascii=False)}")
    return json.dumps(rep, ensure_ascii=False)


if __name__ == "__main__":
    app.run(host='0.0.0.0', port=8080, debug=False)
